package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author ：hushengjin
 */

@Controller
@RequestMapping("/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map searchMap, Model model) {

        //替换特殊字符
        handlerSearchMap(searchMap);

        //调用skuFeign微服务
        Map resultMap = skuFeign.search(searchMap);
        model.addAttribute("result", resultMap);
        //数据回显
        model.addAttribute("searchMap", searchMap);
        //请求地址
        String[] urls = url(searchMap);
        model.addAttribute("url", urls[0]);
        model.addAttribute("sortUrl", urls[1]);

        //分页计算
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("total").toString()),     //总记录数
                Integer.parseInt(resultMap.get("pageNum").toString()),      //当前页
                Integer.parseInt(resultMap.get("pageSize").toString())      //每页条数
        );
        model.addAttribute("page", page);
        return "search";
    }

    /**
     * 替换特殊字符
     *
     * @param searchMap
     */
    public void handlerSearchMap(Map<String,String> searchMap){
        if(searchMap!=null){
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                if(entry.getKey().startsWith("spec_")){
                    entry.setValue(entry.getValue().replace("+","%2B"));
                }
            }
        }
    }

    /**
     * 组装url
     *
     * @param searchMap
     * @return
     */
    public String[] url(Map<String, String> searchMap) {
        //URL迁至不变的地址
        String url = "/search/list";
        String sortUrl = "/search/list";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            sortUrl += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();
                if (key.equalsIgnoreCase("pageNum")) {
                    //跳过分页,分页不拼接url
                    continue;
                }
                url += key + "=" + entry.getValue() + "&";
                if (key.equals("sortRule" ) || key.equals("sortField")) {
                    continue;
                }
                sortUrl += key + "=" + entry.getValue() + "&";
            }
            url = url.substring(0, url.length() - 1);
            sortUrl = sortUrl.substring(0, sortUrl.length() - 1);
        }
        return new String[]{url, sortUrl};
    }

}
